package gold.github.CloudCenter.sevice.Impl;

import com.alibaba.fastjson.JSON;
import gold.github.CloudCenter.mapper.UserMapper;
import gold.github.CloudCenter.model.User;
import gold.github.CloudCenter.model.UserExample;
import gold.github.CloudCenter.model.WeChat.WeChatLoginModel;
import gold.github.CloudCenter.model.WeChat.WeChatResultModel;
import gold.github.CloudCenter.sevice.IUserService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author: XYBH
 * @Description:
 * @Date: Created in 2020/4/26 0026 0:44
 * @Modified:
 */
@Service
public class UserServiceImpl implements IUserService {
    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.secret}")
    private String secret;

    @Resource
    private UserMapper userMapper;

    @Override
    public WeChatResultModel<User> weChatLogin(WeChatLoginModel model) {
        {
            WeChatResultModel<User> result = null;
            try {
                String json;
                OkHttpClient client = new OkHttpClient();
                String GRANTTYPE = "authorization_code";
                Request request = new Request.Builder()
                        .url("https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + model.getCode() + "&grant_type=" + GRANTTYPE)
                        .build();
                Response response = client.newCall(request).execute();
                json = response.body() != null ? response.body().string() : null;
                result = JSON.parseObject(json, WeChatResultModel.class);
                if (result != null && result.getErrcode() == null) {
                    // 去数据库 检查 openId 是否存在 不存在就新建用户
                    UserExample userExample = new UserExample();
                    userExample.createCriteria()
                            .andOpenIdEqualTo(result.getOpenId());
                    List<User> users = userMapper.selectByExample(userExample);
                    User user = users.size()!=0?users.get(0):null;

                    if (user == null || user.getUserId() == null) {
                        // 不存在，就是第一次登录：新建用户信息
                        user = new User();
                        user.setUserId(UUID.randomUUID().toString());
                        user.setOpenId(result.getOpenId());
                        user.setLoginTime(new Date());
                        user.setAuth(1);
                        userMapper.insert(user);
                    } else {
                        //如果存在，就不是第一次登录，更新最后登录时间
                        user.setLoginTime(new Date());
                        userMapper.updateByPrimaryKeySelective(user);
                    }
                    result.setUser(user);
                } else {
                    System.out.println(json);
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

            return result;
        }
    }

    @Override
    public User getUserByUserId(String userId) {
        return userMapper.selectByPrimaryKey(userId);
    }
}
